package com.zyx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zyx.constants.RetCode;
import com.zyx.dto.ResponseDto;
import com.zyx.resource.DynProperties;
import com.zyx.service.RequestMsgService;
import com.zyx.utils.DateTimeUtil;
import com.zyx.utils.DynamicMsgUtils;
import com.zyx.constants.Constants;
import com.zyx.constants.ChannelMap;
import com.zyx.service.RedisService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.zyx.constants.Constants.*;

/**
 * 描述说明: 心跳报文解析
 *
 * @author DQing
 * @version 1.0
 * @className HeartRequestMsgServiceImpl
 * @date 2020/3/31 16:39
 */
@Slf4j
@Service
public class HeartRequestMsgServiceImpl implements RequestMsgService {

    @Autowired
    RedisService redisService;
    @Autowired
    DynProperties dynProperties;

    @Override
    public String msgType() {
        return Constants.HEART_REPORT_URI;
    }

    @Override
    public void parseMsg(ChannelHandlerContext ctx, String content) {
        log.info("接收到终端的心跳报文内容：{}",content);
        Map<String,Object> infoMap = JSON.parseObject(content);
        String deviceNo = (String) infoMap.get(DEVICE_CODE);
        Channel channel = ctx.channel();
        if(checkDeviceNo(channel, deviceNo)){
            ChannelMap.addDeviceChannel(deviceNo,channel);
            responseHeartInfo(channel,0);
        }else {
            log.error("#平台未发现设备：{}，断开设备链路",deviceNo);
            responseHeartInfo(channel,1);
            channel.close();
        }
    }


    /**
     * 鉴权平台设备是否存在
     * @param deviceNo
     */
    private boolean checkDeviceNo(Channel channel,String deviceNo){
        Object value = redisService.get(Constants.REDIS_PREFIX+deviceNo);
        if(StringUtils.isEmpty(value)){
            return false;
        }else{
            log.info("业务平台存在该设备编号，对应value值为：{}",value);
            if("1".equals(value)){
                log.info("业务平台存储的为设备编号初始值，调用设备查询接口，获取设备信息");
                DynamicMsgUtils.requestMsg(channel,null,DEVICE_BASIC_INFO_URI,HTTP_METHOD_GET);
            }
            return true;
        }
    }

    /**
     * 心跳报文响应
     * @param channel
     */
    private void responseHeartInfo(Channel channel,int code){
        Map<String,Object> subMap = new HashMap<>();
        subMap.put(DEVICE_TIME, DateTimeUtil.format(new Date(),DateTimeUtil.DATE_TIME_PATTERN));
        ResponseDto responseDto = new ResponseDto();
        responseDto.setData(subMap);
        responseDto.setResponseURL(NOTIFICATION_RESPONSE_URI);
        responseDto.setCode(code);
        String message = null;
        if(code == 0) {
            message = "成功";
        }else {
            message = "失败";
        }
        responseDto.setMessage(message);
        JSONObject resJson = (JSONObject) JSON.toJSON(responseDto);
        DynamicMsgUtils.responseMsg(channel,resJson.toString(),true);
    }

}
